package com.wb.base.refreshview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

/**
 * Created by AJiang on 16/9/22.
 * 刷新封装
 */

public class PtrHeaderFrameLayout extends PtrHTFrameLayout implements IRefresh{
    private long refreshTime;
    private boolean isRefreshEnable = true;
    private OnRefreshListener onRefreshListener;

    public PtrHeaderFrameLayout(Context context) {
        super(context);
        initView();

    }

    public PtrHeaderFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public PtrHeaderFrameLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView();
    }

    private void initView() {
        HeaderView header1 = new HeaderView(getContext());
        setDurationToClose(500);
        setDurationToCloseHeader(1000);
        setKeepHeaderWhenRefresh(true);
        setPullToRefresh(false);
        setRatioOfHeaderHeightToRefresh(1.2f);
        setResistance(1.7f);
        setHeaderView(header1);
        addPtrUIHandler(header1);
        setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                if (isRefreshEnable) {
                    return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
                } else {
                    return false;
                }
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                refreshTime = System.currentTimeMillis();
                if (onRefreshListener != null) {
                    onRefreshListener.onRefresh();
                }
            }
        });

    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            refreshComplete();
        }
    };

    /*禁止刷新*/
    @Override
    public void disableRefreshing() {
        isRefreshEnable = false;
    }

    /*允许刷新*/
    @Override
    public void enableRefreshing() {
        isRefreshEnable = true;
    }

    /*完成刷新*/
    @Override
    public void completeRefresh() {
        long ctime = System.currentTimeMillis();
        ctime = ctime - refreshTime;
        postDelayed(runnable, ctime > 1500 ? 1000 : 1500);
    }

    @Override
    public void isRefreshing(boolean isRefreshing) {

    }
    @Override
    public void setOnRefreshListener(OnRefreshListener listener) {
        this.onRefreshListener = listener;
    }
}
